/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmTablaAuxiliarDet.java
 *
 * Created on 19-ago-2011, 20:59:39
 */

package GUI;

import TablasAuxiliares.TACaracteresHobbies;
import TablasAuxiliares.TAHobbies;
import TablasAuxiliares.TAModalidadesHobbies;
import Util.GestorErrores;
import javax.swing.JOptionPane;
import Util.Varios;

/**
 *
 * @author Javi
 */
public class frmTAHobbyDet extends javax.swing.JDialog {

    //Indica la operación que se está realizando
    private char _cOperacion;
    //Referencia al formulario padre
    private frmTAHobby _frmPadre;
    //Referencia al objeto de datos principal
    private TAHobbies _oTAHobby;

    /** Creates new form frmTablaAuxiliarDet */
    public frmTAHobbyDet(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(jButtonAceptar);
    }

    /** Creates new form frmTablaAuxiliarDet */
    public frmTAHobbyDet(frmTAHobby parent, boolean modal) {
        super(parent, modal);
        this._frmPadre = parent;
        //Inicializo la referencia al objeto de datos del formulario padre.
        this._oTAHobby = parent.getoObjetoDatos();
        initComponents();
        //Los combos se cargan a partir de las tablas 1 SOLA VEZ, al crear el formulario.
        this.cargarCombos();
        getRootPane().setDefaultButton(jButtonAceptar);
    }

    /*
     * Este método captura los datos introducidos por el usuario y los carga en los atributos
     * correspondientes de la clase.
     */
    private void pantallaAClase(){
        this._oTAHobby.setsCodigo( this.jTextFieldCod.getText() );
        this._oTAHobby.setsDescripcion( this.jTextFieldDescrip.getText() );
        this._oTAHobby.setsModalidad( Varios.getClaveItemCombo (this.jCBModHob));
        this._oTAHobby.setsCaracter( Varios.getClaveItemCombo (this.jCBCarHob));
    }

    /*
     * Este método carga los atributos de la clase los controles del formulario de entrada.
     */
    private void claseAPantalla(){
        this.jTextFieldCod.setText( this._oTAHobby.getsCodigo() );
        this.jTextFieldDescrip.setText(  this._oTAHobby.getsDescripcion() );
        Varios.seleccionaItemCombo (jCBModHob, this._oTAHobby.getsModalidad());
        Varios.seleccionaItemCombo (jCBCarHob, this._oTAHobby.getsCaracter());
    }

    public void inicializaFormulario ( char cOperacion ){
        //Inicializo el código de operación
        this._cOperacion = cOperacion;
        //Carga los datos de la clase
        this.claseAPantalla();
        //Inicializa los controles necesarios
        this.inicializaControles();
    }

    /*
     * Este método carga y habilita/inhabilita los controles que sean necesarios 
     */
    private void inicializaControles (){
        //Actualizo el título de la ventana en función de la operación.
        this.setTitle( this._frmPadre.getoObjetoDatos().getsDescripTabla() + " - " + Varios.getLiteralOperacion(this._cOperacion) );
        if ( this._cOperacion == 'C' || this._cOperacion == 'B'){
            jTextFieldCod.setEditable( false );
            jTextFieldDescrip.setEditable( false );
            jCBModHob.setEnabled(false);
            jCBCarHob.setEnabled(false);
        }else{
            if ( this._cOperacion == 'A')
                jTextFieldCod.setEditable( true );
            else
                jTextFieldCod.setEditable( false );
            jTextFieldDescrip.setEditable( true );
            jCBModHob.setEnabled(true);
            jCBCarHob.setEnabled(true);
        }
    }

    /*
     * Inicializa los combos a partir de las tablas auxiliares en forma "codigo - descripcion"
     */
    private void cargarCombos(){
        Varios.cargaCombo (jCBModHob, new TAModalidadesHobbies());
        Varios.cargaCombo (jCBCarHob, new TACaracteresHobbies());
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCod = new javax.swing.JTextField();
        jTextFieldDescrip = new javax.swing.JTextField();
        jButtonAceptar = new javax.swing.JButton();
        jButtonCancelar = new javax.swing.JButton();
        jCBModHob = new javax.swing.JComboBox();
        jCBCarHob = new javax.swing.JComboBox();
        jLabel32 = new javax.swing.JLabel();
        jLabel34 = new javax.swing.JLabel();

        setResizable(false);

        jLabel1.setText("Código:");

        jLabel2.setText("Descripción:");

        jButtonAceptar.setText("Aceptar");
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });

        jButtonCancelar.setText("Cancelar");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        jCBModHob.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jCBCarHob.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel32.setText("Modalidad:");

        jLabel34.setText("Caracter:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel32, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel34, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextFieldDescrip, javax.swing.GroupLayout.DEFAULT_SIZE, 318, Short.MAX_VALUE)
                            .addComponent(jCBModHob, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextFieldCod, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCBCarHob, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(123, 123, 123)
                        .addComponent(jButtonAceptar)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldCod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCBModHob, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel32))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCBCarHob, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel34))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldDescrip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAceptar)
                    .addComponent(jButtonCancelar))
                .addGap(17, 17, 17))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
        boolean bResultadoOK = false;
        this.pantallaAClase ();
        //Inicializo el vector global de errores
        GestorErrores.getInstancia().getvErrores().clear();
        if (this._cOperacion == 'A')    //Alta
            bResultadoOK = this._oTAHobby.insert();
        else if (this._cOperacion == 'M')    //Actualizacion
            bResultadoOK = this._oTAHobby.update();
        else if (this._cOperacion == 'B'){    //Borrado
            //Pedir confirmación para borrar
            if ( JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog( null, "Va a borrar el registro \n¿Está seguro?" ,"Aviso", JOptionPane.YES_NO_OPTION))
                bResultadoOK = this._oTAHobby.delete();
            else
                return;     //Se cancela la operación
        }else if (this._cOperacion == 'C')    //Consulta
            bResultadoOK = true;

        if ( !bResultadoOK ){
            //Si ha habido errores informo de ellos
            String mensaje = "¡Error en la operación!" + "\n";
            for (int i= 0; i< GestorErrores.getInstancia().getvErrores().size(); i++)
                mensaje = mensaje + GestorErrores.getInstancia().getvErrores().get(i) + "\n";
            JOptionPane.showMessageDialog( null, mensaje,"Aviso", JOptionPane.WARNING_MESSAGE);
        }else{
            //Si no ha habido errores doy mensaje de información de la operación
            if (this._cOperacion == 'A')    //Alta
                JOptionPane.showMessageDialog( null, "Alta realizada","Aviso", JOptionPane.INFORMATION_MESSAGE);
            else if (this._cOperacion == 'M')    //Actualizacion
                JOptionPane.showMessageDialog( null, "Modificación realizada","Aviso", JOptionPane.INFORMATION_MESSAGE);
            else if (this._cOperacion == 'B')    //Borrado
                JOptionPane.showMessageDialog( null, "Baja realizada","Aviso", JOptionPane.INFORMATION_MESSAGE);
            //Si la operación es una CONSULTA no doy ningún aviso.
            //Actualizo la vista de los datos en el formulario padre
            this._frmPadre.actualizarVista("");
        }
        //Ocultar la ventana solo si el resultado ha sido OK.
        setVisible ( (bResultadoOK)? false:true );
    }//GEN-LAST:event_jButtonAceptarActionPerformed

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        setVisible ( false );
    }//GEN-LAST:event_jButtonCancelarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JComboBox jCBCarHob;
    private javax.swing.JComboBox jCBModHob;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel32;
    private javax.swing.JLabel jLabel34;
    private javax.swing.JTextField jTextFieldCod;
    private javax.swing.JTextField jTextFieldDescrip;
    // End of variables declaration//GEN-END:variables

}
